using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Services;
using System.Data;

namespace Lzfy_Refund_Service.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "Admin,SystemAdmin")]
    public class SystemMonitorController : ControllerBase
    {
        private readonly ILogger<SystemMonitorController> _logger;
        private readonly DatabaseHealthCheckService _dbHealthService;
        private readonly IDatabaseConfigurationService _dbConfigService;
        private readonly ILoggerFactory _loggerFactory;

        public SystemMonitorController(
            ILogger<SystemMonitorController> logger,
            DatabaseHealthCheckService dbHealthService,
            IDatabaseConfigurationService dbConfigService,
            ILoggerFactory loggerFactory)
        {
            _logger = logger;
            _dbHealthService = dbHealthService;
            _dbConfigService = dbConfigService;
            _loggerFactory = loggerFactory;
        }

        /// <summary>
        /// 获取数据库连接健康状态
        /// </summary>
        [HttpGet("database-health")]
        public IActionResult GetDatabaseHealth()
        {
            try
            {
                var healthStatus = _dbHealthService.GetDatabasesHealth();
                
                var result = new
                {
                    sqlServer = new
                    {
                        isHealthy = healthStatus.SqlServerHealthy,
                        lastCheckTime = healthStatus.LastSqlServerCheckTime,
                        connectionString = MaskConnectionString(_dbConfigService.GetDefaultConnection())
                    },
                    oracle = new
                    {
                        isHealthy = healthStatus.OracleHealthy,
                        lastCheckTime = healthStatus.LastOracleCheckTime,
                        connectionString = MaskConnectionString(_dbConfigService.GetHisOracleConnection())
                    },
                    timestamp = DateTime.Now
                };
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取数据库健康状态时发生错误");
                return StatusCode(500, new { error = "获取数据库健康状态时发生错误" });
            }
        }

        /// <summary>
        /// 手动触发数据库健康检查
        /// </summary>
        [HttpPost("trigger-database-check")]
        public async Task<IActionResult> TriggerDatabaseHealthCheck()
        {
            try
            {
                // 创建一个新的连接并测试
                var sqlFactory = new ResilientSqlConnectionFactory(
                    _dbConfigService.GetDefaultConnection(),
                    _loggerFactory.CreateLogger<ResilientSqlConnectionFactory>());
                
                var oracleFactory = new ResilientOracleConnectionFactory(
                    _dbConfigService.GetHisOracleConnection(),
                    _loggerFactory.CreateLogger<ResilientOracleConnectionFactory>());
                
                bool sqlServerResult = false;
                bool oracleResult = false;
                
                try
                {
                    using var sqlConn = await sqlFactory.CreateAndOpenConnectionAsync();
                    sqlServerResult = sqlConn.State == System.Data.ConnectionState.Open;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "SQL Server连接测试失败");
                }
                
                try
                {
                    using var oracleConn = await oracleFactory.CreateAndOpenConnectionAsync();
                    oracleResult = oracleConn.State == System.Data.ConnectionState.Open;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Oracle连接测试失败");
                }
                
                var result = new
                {
                    sqlServerConnected = sqlServerResult,
                    oracleConnected = oracleResult,
                    timestamp = DateTime.Now
                };
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发数据库健康检查时发生错误");
                return StatusCode(500, new { error = "触发数据库健康检查时发生错误" });
            }
        }
        
        /// <summary>
        /// 掩码连接字符串中的敏感信息
        /// </summary>
        private string MaskConnectionString(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                return string.Empty;
                
            // 掩码密码
            var maskedConnectionString = System.Text.RegularExpressions.Regex.Replace(
                connectionString,
                @"(Password|PWD)\s*=\s*[^;]*",
                "$1=******",
                System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
            // 掩码用户ID
            maskedConnectionString = System.Text.RegularExpressions.Regex.Replace(
                maskedConnectionString,
                @"(User ID|UID)\s*=\s*[^;]*",
                "$1=******",
                System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
            return maskedConnectionString;
        }
    }
}